/**
 * 怀旧模式
 */

import MapControl = require("./MapControl");
import Define from "./SdkTools/Define";
import gamePrefabMgr, { uiPreName } from "./SdkTools/gamePrefabMgr";
import gameShareAdsVideo from "./SdkTools/gameShareAdsVideo";
import PlayData from "./SdkTools/PlayData";
import storage from "./SdkTools/storage";
import Utils from "./SdkTools/Utils";
import timeOVer from "./timeOver";


const {ccclass, property} = cc._decorator;

@ccclass
export default class GameScene extends cc.Component {

    @property(MapControl)
    mapcontrol:MapControl = null

    @property(cc.Sprite)
    map_png:cc.Sprite = null

    @property(cc.SpriteFrame)
    xuankuang:cc.SpriteFrame = null

    @property(cc.Label)
    taskTimeStr:cc.Label = null

    @property(cc.Node)
    tishinode:cc.Node = null

    @property(cc.Node)
    answerPanel:cc.Node = null

    @property(cc.Label)
    titlestr:cc.Label = null

    @property(cc.Node)
    getAnswerBtn:cc.Node = null

    leveldata = null
    levelnum = 0
    tasktime:number = 0

    answerNum = 0 //需要找出的数量
    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.initGame()
    }

    initGame(){
        gameShareAdsVideo.Instance.recording_Video_Start()
        this.getAnswerBtn.active = !0
        this.mapcontrol.resetMap()
        var self = this
        let _data = storage.Instance.getCheckPoint_diff()

        if(PlayData.Instance.checkoutNum == Define.maxCheckNum_huaijiu){
            PlayData.Instance.checkoutNum = Define.maxCheckNum_huaijiu-1
        }

        this.levelnum = PlayData.Instance.checkoutNum+1 //Number(_data[3])  + 1
        
        let png_path = 'huaijiu/level'+this.levelnum + '/png' + this.levelnum
        cc.resources.load(png_path, cc.SpriteFrame, (err, assert)=>{
            if(err) return console.log('err=', err)
            self.map_png.spriteFrame = assert as cc.SpriteFrame
        })
        
        let data_path = 'huaijiu/level'+this.levelnum + '/level' + this.levelnum
        cc.resources.load(data_path, (err, assert)=>{
            if(err) return console.log('err=', err)
            self.leveldata = assert
            self.setLevelData()

            this.tasktime = Define.zhaobutong_maxTime
            this.taskTimeStr.string = '00:00'
            this.unscheduleAllCallbacks()
            this.schedule(()=>{
                if(PlayData.Instance.ispause) return
                self.tasktime--
                if(self.tasktime <= 0){
                    //let sc = self.top.getComponent(TopUi)
                    //sc.cutSchedule()
                    let c_str = Utils.secondsFormat(self.tasktime, false)
                    self.taskTimeStr.string = c_str

                    self.unscheduleAllCallbacks() 
                    self.showGameOver(0)
                }else{
                    let c_str = Utils.secondsFormat(self.tasktime, false)
                    self.taskTimeStr.string = c_str
                }
            },1,99999,0)   
        })
        this.setTiShi()
        this.resetAnswerPng()
    }

    start () {
        cc.director.emit('game_bg1')
    }

    /**
     * 设置关卡
     */
    setLevelData(){
        let points = this.leveldata.json.point
        this.answerNum = points.length
        let img_w = 1316 
        let img_h = 870
        this.map_png.node.removeAllChildren()

        this.titlestr.string = this.leveldata.json.title
        //console.log('打印设置关卡', points)
        for (let index = 0; index < points.length; index++) {
            let point = points[index];
            
            let newnode = new cc.Node()
            let sp1 = newnode.addComponent(cc.Sprite)
            sp1.spriteFrame = null // this.xuankuang
            sp1.type = cc.Sprite.Type.SLICED
            sp1.sizeMode = cc.Sprite.SizeMode.CUSTOM

            // newnode.x = point.x - img_w/2 + point.w/2  
            // newnode.y = img_h - point.y - point.h/2 - img_h/2
            //console.log('打印位置', index, points[index])
            newnode.x = point.x
            newnode.y = point.y
            newnode.width = point.w
            newnode.height = point.h
            newnode.parent = this.map_png.node
            //console.log('打印节点数据', this.map_png.node)
            newnode.name = '' + index
            newnode.on(cc.Node.EventType.TOUCH_END, this.selectAnswer, this)
        }
    }

    /**
     * 展示结束
     */
    showGameOver(type){
        let newnode = cc.instantiate(gamePrefabMgr.Instance.uiPre[uiPreName.timeOver])
        let sc = newnode.getComponent(timeOVer)
        sc.setType(type)
        newnode.parent = cc.director.getScene()
    }

    /**
     * 选择答案
     * @param event 
     */
    selectAnswer(event){
        //console.log('选择答案',event)
        let sp = event.target.getComponent(cc.Sprite)
        if(sp.spriteFrame == null){
            sp.spriteFrame = this.xuankuang
            this.answerNum --
            this.checkAnswerOver(event.target.name)

            let newtexiao = cc.instantiate(gamePrefabMgr.Instance.uiPre[uiPreName.texiao])
            newtexiao.parent = sp.node
            cc.tween(newtexiao)
            .delay(1)
            .removeSelf()
            .start()
        }else{
            cc.tween(sp.node)
            .to(0.1,{scale:0.9})
            .to(0.1,{scale:1})
            .start()
        }
    }

    /**
     * 设置提示道具数量
     */
    setTiShi(){
        let num = cc.find('tinum', this.tishinode).getComponent(cc.Label)
        num.string = ''+storage.Instance.getTiShi()
    }

    /**
     * 提示按钮点击
     */
    tishiBtnClick(){
        if(storage.Instance.getTiShi() <= 0){
            let newnode = cc.instantiate(gamePrefabMgr.Instance.uiPre[uiPreName.addTiShi])
            newnode.parent = cc.director.getScene()
        }else{
            storage.Instance.setTiShi(storage.Instance.getTiShi()-1)
            this.setTiShi()
            
            let pointdata = this.leveldata.json.point
            let length = pointdata.length
            for (let index = 0; index < length; index++) {
                let _name = '' + index
                let sp = cc.find(_name, this.map_png.node).getComponent(cc.Sprite)
                if(sp.spriteFrame == null){
                    this.answerNum --
                    this.checkAnswerOver(_name)
                    sp.spriteFrame = this.xuankuang

                    let newtexiao = cc.instantiate(gamePrefabMgr.Instance.uiPre[uiPreName.texiao])
                    newtexiao.parent = sp.node
                    cc.tween(newtexiao)
                    .delay(1)
                    .removeSelf()
                    .start()
                    break
                }
            }
        }
    }

    /**
     * 获取答案
     
    getAnswerBtnClick(){
        var self = this
        gameShareAdsVideo.Instance.motivational_Video_Show(()=>{
            self.getAnswerBtn.active = !1
            let points = self.leveldata.json.point
            for (let index = 0; index < points.length; index++) {
                let point = points[index];
                
                let newnode = new cc.Node()
                let sp1 = newnode.addComponent(cc.Sprite)
                sp1.spriteFrame = self.xuankuang
                sp1.type = cc.Sprite.Type.SLICED
                sp1.sizeMode = cc.Sprite.SizeMode.CUSTOM
    
                newnode.x = point.x
                newnode.y = point.y
                newnode.width = point.w
                newnode.height = point.h
                newnode.zIndex = -128
                newnode.parent = self.map_png.node
            }
        }, ()=>{})
    }
*/

    /**
     * 获取答案按钮点击 - 修改为倒计时增加60秒
     */
    getAnswerBtnClick() {
        var self = this;
        gameShareAdsVideo.Instance.motivational_Video_Show(() => {
            // self.getAnswerBtn.active = !1;     点击后按钮消失
            self.addTime(60);  // 添加60秒到当前的游戏倒计时
        }, () => {
            // 如果用户选择不观看广告或广告加载失败，你可以选择不执行任何操作或显示一些消息
            console.log('广告未完成，时间未添加');
        });
    }

    /**
     * 增加指定秒数到当前的倒计时
     * @param seconds 要添加的秒数
     */
    addTime(seconds: number) {
        this.tasktime += seconds;
        // 更新显示的倒计时
        let formattedTime = Utils.secondsFormat(this.tasktime, false);
        this.taskTimeStr.string = formattedTime;
        this.updateCountdown();
    }

    /**
     * 更新倒计时的调度器
     */
    updateCountdown() {
        this.unscheduleAllCallbacks();  // 先取消之前的所有调度
        this.schedule(() => {
            if (PlayData.Instance.ispause) return;  // 如果游戏处于暂停状态，则不减少时间
            this.tasktime--;
            if (this.tasktime <= 0) {
                this.taskTimeStr.string = Utils.secondsFormat(0, false);
                this.unscheduleAllCallbacks();
                this.showGameOver(0);  // 时间耗尽，展示游戏结束
            } else {
                this.taskTimeStr.string = Utils.secondsFormat(this.tasktime, false);
            }
        }, 1, this.tasktime, 0);  // 每秒更新一次，直到倒计时结束
    }



    /**
     * 判断是否作答完成
     */
    checkAnswerOver(pngid){
        this.setAnswerPng(pngid)
        //全部作答完成
        if(this.answerNum <= 0){
            let _data = storage.Instance.getCheckPoint_diff()

            if(_data[3][PlayData.Instance.checkoutNum] == 0){
                _data[3][PlayData.Instance.checkoutNum] = 1
                PlayData.Instance.checkoutNum++

                if(_data[3][PlayData.Instance.checkoutNum] != 0 && _data[3][PlayData.Instance.checkoutNum] != 1){
                    _data[3][PlayData.Instance.checkoutNum] = 0
                    storage.Instance.setHightScore(storage.Instance.getHightScore()+1)
                }
                
                storage.Instance.setCheckPoint_diff(_data)
            }else{
                PlayData.Instance.checkoutNum++
            }  
            
            this.unscheduleAllCallbacks() 
            this.scheduleOnce(()=>{
                this.showGameOver(3)
            }, 1)
        }
    }

    /**
     * 设置下面 答案图
     */
    setAnswerPng(pngid){
        //console.log('设置图', pngid)
        let index = 10 - this.answerNum - 1
        let sp = cc.find('sp'+index +'/icon_shield', this.answerPanel).getComponent(cc.Sprite)
        let num = Number(pngid)+1
        let png_path = 'huaijiu/level'+this.levelnum + '/' + num
        cc.resources.load(png_path, cc.SpriteFrame, (err, assert)=>{
            if(err) return console.log('err=', err)
            sp.spriteFrame = assert as cc.SpriteFrame
        })

        let points = this.leveldata.json.point
        let str = cc.find('sp'+index +'/str', this.answerPanel).getComponent(cc.Label)
        let point = points[num-1]
        str.string = '' + point.name

    }
    resetAnswerPng(){
        for (let index = 0; index < 10; index++) {
            let sp = cc.find('sp'+index +'/icon_shield', this.answerPanel).getComponent(cc.Sprite)
            sp.spriteFrame = null
            let str = cc.find('sp'+index +'/str', this.answerPanel).getComponent(cc.Label)
            str.string = ''
        }
    }

    // update (dt) {}

    /**
     * 返回主界面
    */
    backHome(){
        cc.director.loadScene('StartScene')
    }

    /**
     * 设置按钮
     */
    setBtnClick(){
        let newnode = cc.instantiate(gamePrefabMgr.Instance.uiPre[uiPreName.pausepanel])
        newnode.parent = cc.director.getScene()
    }

    /**
     * 复活
    
    reliveGame(){
        var self = this
        this.tasktime = 60
        this.taskTimeStr.string = '00:60'
        this.unscheduleAllCallbacks()
        this.schedule(()=>{
            if(PlayData.Instance.ispause) return
            self.tasktime--
            if(self.tasktime <= 0){
                let c_str = Utils.secondsFormat(self.tasktime, false)
                self.taskTimeStr.string = c_str

                self.unscheduleAllCallbacks() 
                self.showGameOver(0)
            }
            else{
                let c_str = Utils.secondsFormat(self.tasktime, false)
                self.taskTimeStr.string = c_str
            }
        },1,99999,0)   
    }
*/

    /**
     * 复活游戏并重新开始倒计时
     */
    reliveGame() {
        this.tasktime = 60;
        this.taskTimeStr.string = this.formatTime(this.tasktime);
    
        this.unscheduleAllCallbacks();
        this.schedule(() => {   
            if (PlayData.Instance.ispause) {
            } else {
                if (this.tasktime <= 0) {
                    this.taskTimeStr.string = this.formatTime(0);
                    this.unscheduleAllCallbacks();
                    this.showGameOver(0);
                } else {
                    this.tasktime--;
                    this.taskTimeStr.string = this.formatTime(this.tasktime);
                }
            }
        }, 1, cc.macro.REPEAT_FOREVER);
    }
    
    

    /**
     * 格式化时间为 mm:ss 格式
     */
    formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    }




}
